import React, { useState, useEffect } from 'react';
import {
  Container,
  Typography,
  TextField,
  Button,
  Paper,
  Box,
  Alert,
  CircularProgress,
  Card,
  CardContent,
  Grid,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TableContainer,
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableCell
} from '@mui/material';

// 信用评分规则
const CREDIT_RULES = {
  MIN_SCORE: 600,
  MAX_SCORE: 850,
  LOAN_LIMITS: {
    600: 1000,    // 600分可借1000
    650: 2000,    // 650分可借2000
    700: 5000,    // 700分可借5000
    750: 10000,   // 750分可借10000
    800: 20000,   // 800分可借20000
    850: 50000    // 850分可借50000
  }
};

// 获取可借款额度
const getLoanLimit = (creditScore) => {
  const scores = Object.keys(CREDIT_RULES.LOAN_LIMITS)
    .map(Number)
    .sort((a, b) => a - b);

  for (let i = scores.length - 1; i >= 0; i--) {
    if (creditScore >= scores[i]) {
      return CREDIT_RULES.LOAN_LIMITS[scores[i]];
    }
  }
  return 0;
};

const Borrow = ({ user }) => {
  const [amount, setAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [showVerificationDialog, setShowVerificationDialog] = useState(false);
  const [creditProof, setCreditProof] = useState(null);
  const [userData, setUserData] = useState(null);
  const [allLoans, setAllLoans] = useState([]);

  // 获取用户数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch user data
        const userResponse = await fetch(`http://localhost:3001/api/user/${user.id}`);
        const userData = await userResponse.json();
        if (userData.success) {
          setUserData(userData.user);
        }

        // Fetch all loans
        const loansResponse = await fetch('http://localhost:3001/api/all-loans');
        const loansData = await loansResponse.json();
        if (loansData.success) {
          setAllLoans(loansData.loans);
        }
      } catch (err) {
        console.error('Error fetching data:', err);
        setError('获取数据失败');
      }
    };

    if (user) {
      fetchData();
    }
  }, [user]);

  // 获取最新的信用证明
  useEffect(() => {
    const fetchLatestCreditProof = async () => {
      try {
        console.log('Fetching credit proof for user:', user.id);
        const response = await fetch(`http://localhost:3001/api/credit-proofs/${user.id}/latest`);
        const data = await response.json();
        console.log('Credit proof response:', data);
        if (data.success) {
          setCreditProof(data.proof);
          console.log('Credit proof set:', data.proof);
        } else {
          console.log('Failed to get credit proof:', data.message);
        }
      } catch (err) {
        console.error('获取信用证明失败:', err);
      }
    };

    if (user) {
      fetchLatestCreditProof();
    }
  }, [user]);

  const handleBorrow = async () => {
    if (!amount || amount <= 0) {
      setError('请输入有效的借款金额');
      return;
    }

    if (!creditProof) {
      setError('请先生成信用证明');
      return;
    }

    setShowVerificationDialog(true);
  };

  const handleConfirmBorrow = async () => {
    if (!verificationCode) {
      setError('请输入验证口令');
      return;
    }

    setLoading(true);
    setError('');
    setSuccess('');

    try {
      const response = await fetch('http://localhost:3001/api/borrow', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: user.id,
          amount: parseInt(amount),
          creditProof: creditProof,
          verificationCode
        }),
      });

      const data = await response.json();

      if (data.success) {
        setSuccess('借款申请成功！');
        setAmount('');
        setVerificationCode('');
        setShowVerificationDialog(false);
        // 刷新用户数据
        const userResponse = await fetch(`http://localhost:3001/api/user/${user.id}`);
        const userData = await userResponse.json();
        if (userData.success) {
          setUserData(userData.user);
        }
      } else {
        setError(data.message || '借款失败');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  if (!user) {
    return (
      <Container maxWidth="md" sx={{ mt: 4 }}>
        <Alert severity="warning">请先登录</Alert>
      </Container>
    );
  }

  return (
    <Container maxWidth="md" sx={{ mt: 4 }}>
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h5" gutterBottom>
                借款申请
              </Typography>
              <Typography variant="body1" color="text.secondary">
                请先在"信用证明"页面生成验证口令，然后在下方输入借款金额和验证口令。
              </Typography>
              <Typography variant="body1" color="primary" sx={{ mt: 2 }}>
                当前余额：{(userData?.balance || 0).toFixed(2)} 元
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h5" gutterBottom>
              借款信息
            </Typography>

            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}

            {success && (
              <Alert severity="success" sx={{ mb: 2 }}>
                {success}
              </Alert>
            )}

            <Box sx={{ mb: 3 }}>
              <TextField
                fullWidth
                label="借款金额"
                type="number"
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                disabled={loading}
                sx={{ mb: 2 }}
              />

              {!creditProof && (
                <Alert severity="warning" sx={{ mb: 2 }}>
                  请先在"信用证明"页面生成信用证明
                </Alert>
              )}

              {creditProof && (
                <Alert severity="info" sx={{ mb: 2 }}>
                  当前信用分：{userData?.creditScore || creditProof.creditScore}，可借额度：{getLoanLimit(userData?.creditScore || creditProof.creditScore)}
                </Alert>
              )}

              <Button
                variant="contained"
                color="primary"
                onClick={handleBorrow}
                disabled={loading || !amount || !creditProof}
                fullWidth
              >
                {loading ? <CircularProgress size={24} /> : '申请借款'}
              </Button>
            </Box>

            <Box sx={{ mt: 2 }}>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                提示：
              </Typography>
              <Box component="ul" sx={{ pl: 2, mt: 0 }}>
                <Typography component="li" variant="body2" color="text.secondary">
                  借款前请先在"信用证明"页面生成验证口令
                </Typography>
                <Typography component="li" variant="body2" color="text.secondary">
                  验证口令有效期为24小时
                </Typography>
                <Typography component="li" variant="body2" color="text.secondary">
                  借款期限为30天
                </Typography>
                <Typography component="li" variant="body2" color="text.secondary">
                  按时还款将提高您的信用分
                </Typography>
                <Typography component="li" variant="body2" color="text.secondary">
                  逾期还款将降低您的信用分
                </Typography>
              </Box>
            </Box>
          </Paper>
        </Grid>

        <Grid item xs={12}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h5" gutterBottom>
              借款记录
            </Typography>
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>时间</TableCell>
                    <TableCell>金额</TableCell>
                    <TableCell>到期时间</TableCell>
                    <TableCell>状态</TableCell>
                    <TableCell>借款人</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {allLoans.map((loan) => (
                    <TableRow key={loan.id}>
                      <TableCell>
                        {new Date(loan.timestamp).toLocaleString()}
                      </TableCell>
                      <TableCell>{loan.amount.toFixed(2)} 元</TableCell>
                      <TableCell>
                        {new Date(loan.dueDate).toLocaleString()}
                      </TableCell>
                      <TableCell>
                        {loan.status === 'pending' ? '进行中' : '已完成'}
                      </TableCell>
                      <TableCell>{loan.username}</TableCell>
                    </TableRow>
                  ))}
                  {allLoans.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={5} align="center">
                        暂无借款记录
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        </Grid>
      </Grid>

      <Dialog open={showVerificationDialog} onClose={() => setShowVerificationDialog(false)}>
        <DialogTitle>验证信用证明</DialogTitle>
        <DialogContent>
          <Typography variant="body2" sx={{ mb: 2 }}>
            请输入从"信用证明"页面获取的验证口令：
          </Typography>
          <TextField
            fullWidth
            label="验证口令"
            value={verificationCode}
            onChange={(e) => setVerificationCode(e.target.value)}
            disabled={loading}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowVerificationDialog(false)}>取消</Button>
          <Button
            onClick={handleConfirmBorrow}
            variant="contained"
            disabled={loading || !verificationCode}
          >
            {loading ? <CircularProgress size={24} /> : '确认借款'}
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default Borrow; 